<?php

namespace backend\controllers;

use common\models\Admin;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;

class AdminController extends BaseController
{
    /**
     * 这里是登录界面.
     */
    public function actionLogin()
    {
        var_dump($_SERVER);exit;
        $this->layout = 'common';
        if($this->isGet())
        {
            return $this->render('login');
        }
        if($this->isPost() && $this->isAjax())
        {
            $data = $this->post();
            if(!array_key_exists('email',$data) || !array_key_exists('pass',$data))
            {
                return $this->renderJson([],'信息不完整',ConstantService::$response_fail);
            }

            if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$data['email']))
            {
                return $this->renderJson([],'请输入正确邮箱',ConstantService::$response_fail);
            }

            // 开始登录.
            $admin_user = Admin::findOne(['email'=>$data['email']]);

            if(!$admin_user)
            {
                return $this->renderJson([],'登录失败,请检查所输入的用户名和密码!',ConstantService::$response_fail);
            }

            // 开始验证正确的密码.
            if($admin_user['password'] != md5(md5($data['pass']).$this->salt))
            {
                return $this->renderJson([],'登录失败,请检查所输入的用户名和密码!',ConstantService::$response_fail);
            }

            // 这里开始其他操作.记住用户的密码.
            $token = $admin_user->primaryKey . '#' . $this->genToken($admin_user);
            $this->addCookie($this->auth_cookie, $token,7200);
            $admin_user->setAttributes([
                'last_ip'   => CommonService::getIP(),
                'last_time' => date('Y-m-d H:i:s')
            ]);
            $admin_user->save(0);
            return $this->renderJson([],'登录成功',ConstantService::$response_success);
        }

        return $this->redirect(GlobalUrlService::buildAdminUrl('/admin/login'));
    }

    /**
     * 用户退出.
     */
    public function actionLogout()
    {
        $this->removeCookie($this->auth_cookie);
        return $this->redirect(GlobalUrlService::buildAdminUrl('/admin/login'));
    }
}